//
//  XHKSDrawAdViewController.m
//  XHAdSDKTest
//
//  Created by 昱胜 on 2022/7/22.
//

#import "XHKSDrawAdViewController.h"
#import "KSAdDrawDemoCell.h"
#import "KSDrawAdCell.h"
#import "KSDrawCollectionViewCell.h"
//广告头文件
#import <XHAdSDK/XHAdSDK.h>

@interface XHKSDrawAdViewController ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, KSDrawAdsManagerDelegate, KSDrawAdDelegate,XHDrawAdDataDelegate>
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, copy) NSArray *dataArray;

@property (nonatomic, strong) KSDrawAdsManager *drawAdsManager;

@property (nonatomic, strong) UITableViewCell *lastCell;

@end

@implementation XHKSDrawAdViewController

- (NSArray *)_formatSDKStringWithFileName:(NSString *)fileName {
    NSURL *testJsonURL = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
    // 读取文件内容
    NSData *testData = [NSData dataWithContentsOfURL:testJsonURL];
    NSArray *urlArray = [NSJSONSerialization JSONObjectWithData:testData options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray *mutAry = [NSMutableArray new];
    for (NSInteger i = 0; i < urlArray.count; i++) {
        NSString *str = urlArray[i];
        KSAdDrawModel *model = [[KSAdDrawModel alloc] init];
        model.videoUrl = str;
        model.index = i;
        [mutAry addObject:model];
    }
    return mutAry;
}

#pragma mark - View Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.backButton];

    self.collectionView.frame = CGRectMake(0, 88, self.view.frame.size.width, self.view.frame.size.height-88);
    
//    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(@64);
//        make.left.equalTo(@10);
//        make.width.height.equalTo(@(60));
//    }];


    [self loadDrawAd];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

/// 隐藏 状态栏
- (BOOL)prefersStatusBarHidden {
    return YES;
}

#pragma mark - Private
- (void)loadDrawAd {
    NSArray *modelArray = [self _formatSDKStringWithFileName:@"demo_draw_video_url"];
    self.dataArray = modelArray;
    
    XHAdCenter * center = [XHAdCenter new];
    XHDrawAdData * data = [XHDrawAdData new];
    data.userId = @"";
    data.adCount = 1;
    data.rootViewController = self;
    data.drawAdDelegate = self;
    __weak typeof(self) weakSelf = self;
    [center xh_showDrawAd:data appId:@"289150002507284541" adType:XHAdType_KS complate:^(NSArray<__kindof KSDrawAd *> * _Nonnull adViewAry) {
        NSInteger index = MIN(weakSelf.dataArray.count / 2, 2);
        NSMutableArray *mutAry = [weakSelf.dataArray mutableCopy];
        for (NSInteger i = 0; i < adViewAry.count; i++) {
            KSDrawAd *drawAd = adViewAry[i];
            drawAd.delegate = weakSelf;
            //手动控制播放状态
            drawAd.controlPlayState = YES;
            [mutAry insertObject:drawAd atIndex:(index + i)];
        }
        weakSelf.dataArray = mutAry;
        [weakSelf.collectionView reloadData];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id model = self.dataArray[indexPath.row];
    if ([model isKindOfClass:[KSAdDrawModel class]]) {
        KSAdDrawModel *tmpModel = (KSAdDrawModel *)model;
        KSAdDrawDemoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(KSAdDrawDemoCell.class)];
        if (!cell) {
            cell = [[KSAdDrawDemoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(KSAdDrawDemoCell.class)];
        }
        [cell refreshWithModel:tmpModel];
        return cell;
    } else if ([model isKindOfClass:[KSDrawAd class]]) {
        KSDrawAd *drawAd = (KSDrawAd *)model;
        KSDrawAdCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(KSDrawAdCell.class)];
        if (!cell) {
            cell = [[KSDrawAdCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(KSDrawAdCell.class)];
        }
        [cell refreshWithDrawAd:drawAd];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class)];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        }
        return cell;
    }
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    id model = self.dataArray[indexPath.row];
    if ([model isKindOfClass:[KSDrawAd class]]) {
        KSDrawAd *drawAd = (KSDrawAd *)model;
        KSDrawCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"drawcell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        [cell refreshWithDrawAd:drawAd];
        return cell;
    } else {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"customcell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        UILabel *label = [cell viewWithTag:1000];
        if (!label) {
            label = [UILabel new];
            label.textColor = [UIColor redColor];
            label.font = [UIFont systemFontOfSize:20];
            label.tag = 1000;
            [cell addSubview:label];
            label.frame = cell.contentView.bounds;
            label.textAlignment = NSTextAlignmentCenter;
        }
        label.text = [NSString stringWithFormat:@"第%lld个cell --> 横滑", (long long)indexPath.row];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    id model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[KSDrawAd class]]) {
        KSDrawAd *drawAd = (KSDrawAd *)model;
        [drawAd play];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    id model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[KSDrawAd class]]) {
        KSDrawAd *drawAd = (KSDrawAd *)model;
        [drawAd pause];
    }
}

#pragma mark - KSDrawAdDelegate
- (void)drawAdViewWillShow:(KSDrawAd *)drawAd {
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw视频展示" stringByAppendingString:NSStringFromSelector(_cmd)]];
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)drawAdDidClick:(KSDrawAd *)drawAd {
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw广告点击回调" stringByAppendingString:NSStringFromSelector(_cmd)]];
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)drawAdDidShowOtherController:(KSDrawAd *)drawAd interactionType:(KSAdInteractionType)interactionType {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)drawAdDidCloseOtherController:(KSDrawAd *)drawAd interactionType:(KSAdInteractionType)interactionType {
    [drawAd play]; // 关闭落地页后自动播放
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)drawAdVideoDidStart:(KSDrawAd *)drawAd {
    NSLog(@"%@", NSStringFromSelector(_cmd));
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw视频开始播放" stringByAppendingString:NSStringFromSelector(_cmd)]];
}

- (void)drawAdVideoDidPause:(KSDrawAd *)drawAd {
    NSLog(@"%@", NSStringFromSelector(_cmd));
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw广告视频暂停播放" stringByAppendingString:NSStringFromSelector(_cmd)]];
}

- (void)drawAdVideoDidResume:(KSDrawAd *)drawAd {
    NSLog(@"%@", NSStringFromSelector(_cmd));
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw广告视频恢复播放" stringByAppendingString:NSStringFromSelector(_cmd)]];
}

- (void)drawAdVideoDidFailed:(KSDrawAd *)drawAd error:(NSError *)error {
    NSLog(@"%@", NSStringFromSelector(_cmd));
//    [[KSBulletScreenManager sharedInstance] showWithText:[@"draw广告视频播放错误" stringByAppendingString:NSStringFromSelector(_cmd)]];
}

- (void)drawAdVideoDidStop:(KSDrawAd *)drawAd finished:(BOOL)finished {
    NSLog(@"%@", NSStringFromSelector(_cmd));
//    [[KSBulletScreenManager sharedInstance] showWithText:[NSString stringWithFormat:@"draw广告视频播放结束%@ finished:%d", NSStringFromSelector(_cmd), finished]];
}

#pragma mark - Action
- (void)backButtonTouchUpInside:(id)sender {
    if (self.navigationController.viewControllers.count <= 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UI Getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = [UIScreen mainScreen].bounds.size;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"customcell"];
        [_collectionView registerClass:[KSDrawCollectionViewCell class] forCellWithReuseIdentifier:@"drawcell"];
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

- (UIButton *)backButton {
    if (_backButton == nil) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"icon_ksad_demo_back"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _backButton.contentMode = UIViewContentModeCenter;
    }
    return _backButton;
}


@end
